package logic

import (
	"gitee.com/kristas/booting-go/framework/common/util/lang"
	"gitee.com/kristas/booting-go/gen_tool/booctl/creator"
	"gitee.com/kristas/booting-go/gen_tool/booctl/util"
	"os"
	"strings"
)

const (
	layerApi        = "api"
	layerService    = "service"
	layerRepository = "repository"
	layerDomain     = "domain"
)

var layersRegis = []string{layerApi, layerService, layerRepository, layerDomain}

var layerAliasMapping = map[string]string{
	layerApi:        layerApi,
	"controller":    layerApi,
	"ctr":           layerApi,
	layerService:    layerService,
	"svc":           layerService,
	layerRepository: layerRepository,
	"repo":          layerRepository,
	layerDomain:     layerDomain,
	"entity":        layerDomain,
}

func GenEntry(debug bool, layers ...string) error {
	if len(layers) == 0 {
		layers = layersRegis
	}
	var creators []creator.FileCreator
	g := creator.NewGoFile("gen", ".tmp", "gen", false)
	creators = append(creators, g)
	var layerArr []string
	for i := range layers {
		layers[i] = layerAliasMapping[strings.ToLower(layers[i])]
		c := creator.NewGoFile(layers[i]+"_generator", ".tmp", "", false)
		creators = append(creators, c)
		layerArr = append(layerArr, lang.NewString(layers[i]).FirstLetterUpper().String())
	}
	g.SetAttribute("Layers", layerArr)
	creators = append(creators, &creator.YamlFile{
		Pkg:          ".tmp",
		Template:     "gen_config",
		SkipIfExists: false,
		FileName:     "config",
	})
	err := creator.NewBatchCreator(creators...).Create()
	if err != nil {
		return err
	}
	if debug {
		return nil
	}
	err = run()
	if err != nil {
		return err
	}
	defer cmd.FmtAll(layers...)
	return cleanTmp()
}

func run() error {
	wd, err := os.Getwd()
	if err != nil {
		return err
	}
	err = os.Chdir(".tmp")
	if err != nil {
		return err
	}
	defer os.Chdir(wd)

	var cmd util.GoCmd
	cmd.Run(".tmp")
	return nil
}

func cleanTmp() error {
	return os.RemoveAll(".tmp")
}
